<template>
<l-layout class="l-tab-page" >
    <l-panel >
        <template #toolLeft >
            <div class="l-panel--item" >
                <el-input :placeholder="$t('请输入名称/编号')"  @keyup.enter.native="hanleSearch" v-model="searchWord" size="mini" >
                    <el-button @click="hanleSearch" slot="append" icon="el-icon-search"></el-button>
                </el-input>
            </div>
        </template>
        <template #toolRight >
            <l-tool-btns @click="handleAdd()" :btnText="$t('通用数据权限')" >
                <el-button-group v-if="lr_hasPageAuth('addDataSource','buttons')">
                    <el-button type="primary" size="mini" @click="handleDAdd()" >{{ $t('数据源数据权限') }}</el-button>
                </el-button-group>
                <el-button-group v-if="lr_hasPageAuth('addForm','buttons')">
                    <el-button type="primary" size="mini" @click="handleCAdd()" >{{ $t('自定义功能数据权限') }}</el-button>
                </el-button-group>
                <l-excel-btns></l-excel-btns>
            </l-tool-btns>
        </template>
        <l-table 
            :columns="columns" 
            :dataSource="tableData" 
            :loading="tableLoading"
            row-key="f_Id"
            :isPage="true"
            :pageTotal="tableTotal"
            :tablePage.sync="tableCurrentPage"

            @loadPageData="turnTablePage"
            >
            <template v-slot:f_Code="scope" >
                {{scope.row.f_Type == 1?scope.row.f_Code:(myModules.find(t=>t.value ==scope.row.f_Code) || {}).label || ''}}
                {{scope.row.f_Type == 3?(datasource.find(t=>t.value ==scope.row.f_Code) || {}).label || '':''}}
            </template>

           
            <template v-slot:f_ObjectType="scope" >
                <el-tag v-if="scope.row.f_ObjectType == 1" size="mini" type="success">{{ $t('角色') }}</el-tag>
                <el-tag v-else size="mini" >{{ $t('人员') }}</el-tag>
            </template>
            <template v-slot:f_Type="scope" >
                <el-tag v-if="scope.row.f_Type == 1" size="mini" type="success">{{ $t('开发功能') }}</el-tag>
                <el-tag v-else-if="scope.row.f_Type == 3" size="mini" type="warning">{{ $t('数据源') }}</el-tag>
                <el-tag v-else size="mini" >{{ $t('自定义功能') }}</el-tag>
            </template>
            <template v-slot:f_CreateDate="scope" >
                {{lr_dateFormat(scope.row.f_CreateDate)}}
            </template>
           

            <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick" ></l-table-btns>
        </l-table>
    </l-panel>

    <l-drawer
        :title="formTitle"
        :visible.sync="formVisible"
        @close="handleCloseForm"
        @opened="handleOpenedForm"
        @ok="handleSave"
        :width="800"
        >
        <my-form ref="form" ></my-form>
    </l-drawer>

    <l-drawer
        :title="cformTitle"
        :visible.sync="cformVisible"
        @close="handleCloseCForm"
        @opened="handleOpenedCForm"
        @ok="handleSave"
        :width="800"
        >
        <c-form ref="cform" ></c-form>
    </l-drawer>

    <l-drawer
        :title="dformTitle"
        :visible.sync="dformVisible"
        @close="handleCloseDForm"
        @opened="handleOpenedDForm"
        @ok="handleSave"
        :width="800"
        >
        <d-form ref="dform" ></d-form>
    </l-drawer>
</l-layout>
</template>

<script>
import { mapGetters } from 'vuex'

const api = window.$api.permission.data
const apiApp = window.$api.mapp.module

import MyForm from './form.vue'
import CForm from './cform.vue'
import DForm from './dform.vue'
export default {
    components:{
        MyForm,
        CForm,
        DForm
    },
    data () {
        return {
            searchWord:'',
            columns: [
                {label:'编码',prop:'f_Code',minWidth:'120'},
                {label:'名称',prop:'f_Name',minWidth:'160'},
                {label:'授权类型',prop:'f_ObjectType',width:'80',align:'center'},
                {label:'授权对象',prop:'f_ObjectId',width:'120',align:'center',formatter:({row,cellValue})=>{
                    if(row.f_ObjectType == 1){
                        this.lr_loadRole(cellValue)
                        return (this.lr_role[cellValue] || {})['f_FullName'] || ''
                    }
                    else{
                        this.lr_loadUsers(cellValue)
                        return this.lr_userName(cellValue)
                    }
                }},
                
                {label:'类型',prop:'f_Type',width:'100',align:'center'},
                {label:'创建人',prop:'f_CreateUserName',width:'100'},
                {label:'创建时间',prop:'f_CreateDate',width:'160'}
            ],
            tableBtns:[
                {prop:'Edit',label:this.$t('编辑'),width:40},
                {prop:'Delete',label:this.$t('删除'),width:40}
            ],

            tableLoading:false,
            tableData:[],
            tableTotal:0,
            tablePageSize:50,
            tableCurrentPage:1,

            formTitle:'',
            formVisible:false,
            formEdit:false,
            formEditRow:null,

            cformTitle:'',
            cformVisible:false,

            dformTitle:'',
            dformVisible:false,

            appList:[]
        };
    },
    async created () {
        const appList = await this.$awaitWraper(apiApp.getList())
        if(appList){
            this.appList = appList.filter(t=>t.f_IsSystem == 2)
        }
    },
    mounted () {
        this.loadTableData()
        this.lr_loadDataSourceList()
    },
    computed:{
        ...mapGetters(["modules"]),
        myModules(){
            const res = []
            const pcList = this.modules.filter(t=>t.f_EnabledMark == 1 && t.f_Target == 'custmerForm')

            res.push(...pcList.map(t=>({...t,value:t.f_ModuleId,label:t.f_FullName})))    
            res.push(...this.appList.map(t=>({...t,value:t.f_Id,label:t.f_Name})))   
            return  res
        },
        datasource(){
            const res = []
            const List = this.lr_dataSource

            res.push(...List.map(t=>({...t,value:t.f_Id,label:t.f_Name})))    
            return  res
        },
    },
    methods:{
        loadTableData(isNotFirst){
            if(!isNotFirst){
                this.tableCurrentPage = 1;
            }
            this.tableLoading = true;
            let queryData = {
                rows:this.tablePageSize,
                page:this.tableCurrentPage,
                sidx:'F_CreateDate DESC',
                keyword:this.searchWord
            }
            api.getPage(queryData).then(res=>{
                const data = this.$deepClone(res.data.data);
                this.tableData = data.rows;
                this.tableTotal = data.records;
                this.tableLoading = false;

            }).catch(()=>{
                this.tableData = [];
                this.tableLoading = false;
            });
        },
        turnTablePage({rows}){
            this.tablePageSize = rows
            this.loadTableData(true)
        },
        hanleSearch(){
            this.loadTableData()
        },
        handleAdd(){
            this.formEdit = false;
            this.showForm('新增数据权限条件')
        },
        handleCAdd(){
            this.formEdit = false;
            this.showCForm('新增自定义功能数据权限条件')
        },
        handleEdit($index,row){  
            this.formEdit = true
            this.formEditRow = row
            if(row.f_Type == 1){
                this.showForm('编辑数据权限条件')
            }
            else if(row.f_Type == 3){
                this.showDForm('编辑数据源数据权限条件')
            }
            else{
                this.showCForm('自定义功能数据权限条件')
            }
        },
        handleDelete($index,row){
            this.$confirm(
                this.$t('此操作将永久删除该数据, 是否继续?'), 
                this.$t('提示'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
            }).then(() => {
                api.remove(row.f_Id).then(()=> {
                    this.$message({
                        type: 'success',
                        message: this.$t('删除成功!')
                    });
                    this.loadTableData()
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: this.$t('已取消删除')
                });          
            });
        },
        async handleSave(showLoading,hideLoading){
            showLoading('加载数据中...')
            if(this.cformVisible){
                await this.handleSaveCForm()
            }else if(this.dformVisible){
                await this.handleSaveDForm()
            }
            else{
                await this.handleSaveForm()
            }
           
            hideLoading()
        },
        async handleSaveForm(){
             if(await this.$refs.form.validateForm()){
                const postData = this.$refs.form.getForm()

                if(this.formEdit){// 修改数据
                    await api.update(this.formEditRow.f_Id,postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('更新成功!')
                    })
                }
                else{// 新增数据
                    await api.add(postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('新增成功!')
                    })
                }

                this.formVisible = false
                this.loadTableData()
            }
        },

        handleCloseForm(){
            this.$refs.form.resetForm()
        },
        handleOpenedForm(){
            if(this.formEdit){
                this.$refs.form.setForm(this.$deepClone(this.formEditRow))
            }
        },
        showForm(text){
            this.formTitle = text
            this.formVisible = true
        },
        showCForm(text){
            this.cformTitle = text
            this.cformVisible = true
        },
        handleCloseCForm(){
            this.$refs.cform.resetForm()
        },
        handleOpenedCForm(){
            if(this.formEdit){
                this.$refs.cform.setForm(this.$deepClone(this.formEditRow))
            }
        },

        async handleSaveCForm(){
             if(await this.$refs.cform.validateForm()){
                const postData = this.$refs.cform.getForm()

                if(this.formEdit){// 修改数据
                    await api.update(this.formEditRow.f_Id,postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('更新成功!')
                    })
                }
                else{// 新增数据
                    await api.add(postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('新增成功!')
                    })
                }

                this.cformVisible = false
                this.loadTableData()
            }
        },
        //数据源数据权限----ADD BY SSY 20220427
        handleDAdd(){
            this.formEdit = false;
            this.showDForm('新增数据源数据权限条件')
        },
        showDForm(text){
            this.dformTitle = text
            this.dformVisible = true
        },
        handleCloseDForm(){
            this.$refs.dform.resetForm()
        },
        handleOpenedDForm(){
            if(this.formEdit){
                this.$refs.dform.setForm(this.$deepClone(this.formEditRow))
            }
        },

        async handleSaveDForm(){
             if(await this.$refs.dform.validateForm()){
                const postData = this.$refs.dform.getForm()

                if(this.formEdit){// 修改数据
                    await api.update(this.formEditRow.f_Id,postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('更新成功!')
                    })
                }
                else{// 新增数据
                    await api.add(postData)
                    this.$message({
                        type: 'success',
                        message: this.$t('新增成功!')
                    })
                }

                this.dformVisible = false
                this.loadTableData()
            }
        },
    }
}
</script>
